package demo.listenner;

import com.rabbitmq.client.Channel;
import demo.common.constants.Constant;
import demo.common.pojo.UserInfo;
import demo.utils.JsonUtil;
import demo.common.utils.MailUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Slf4j
@Configuration
public class SendMailListener {

    @Autowired
    MailUtil mailUtil;

    @RabbitListener(queues = Constant.QUEUE_NAME)
    public void receive(Message message, Channel channel) throws IOException {
        System.out.println(message);

        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        UserInfo userInfo = JsonUtil.fromJson(new String(message.getBody()), UserInfo.class);

        assert userInfo != null;

        try {
            sendMail(userInfo);
//            确认成功
            channel.basicAck(deliveryTag, true);
        }catch (Exception e){
//            失败
            channel.basicNack(deliveryTag, true,true);
            log.error("邮件发送失败 {}", e.getMessage(), e);

        }

    }

    private void sendMail(UserInfo userInfo) {
        mailUtil.setMailSender(userInfo.getEmail(),String.format("%s 感谢你的注册",userInfo.getUserName()),"注册成功");
    }

}
